public class ReversePairs {
    int[] tmp;
    public int reversePairs(int[] record) {
        int n = record.length;
        tmp = new int[n];
        return mergeSort(record, 0, n - 1);
    }

    public int mergeSort(int[] nums, int left, int right) {
        if(left >= right) {
            return 0;
        }
        // 1.从左区间找出 a 个逆序对, 从右区间找出 b 个逆序对, 再一左一右找出 c 个逆序对
        int ret = 0;
        // 2.根据中间点分左右部分
        int mid = left + ((right - left) >> 1);
        // [left, mid] [mid+1, right]
        ret += mergeSort(nums, left, mid);
        ret += mergeSort(nums, mid+1, right);

        // 3.根据单调性一左一右统计逆序对个数,同时合并两个有序数列
        int cur1 = left, cur2 = mid+1;
        int i = 0;
        while(cur1 <= mid && cur2 <= right) {
            if(nums[cur1] <= nums[cur2]) {
                tmp[i++] = nums[cur1++];
            }else {
                // nums[cur1] > nums[cur2]
                ret += mid - cur1 + 1;
                tmp[i++] = nums[cur2++];
            }
        }

        while(cur1 <= mid) {
            tmp[i++] = nums[cur1++];
        }
        while(cur2 <= right) {
            tmp[i++] = nums[cur2++];
        }

        // 4.把合并好的序列放回原数组中
        for(int j = 0; j < right - left + 1; j++) {
            nums[j + left] = tmp[j];
        }
        return ret;
    }
}
